package com.mdp.lcode.ctrl;

import java.util.*;
import java.util.stream.Collectors;

import com.mdp.lcode.entity.FormDefVo;
import com.mdp.lcode.service.FormDataService;
import com.mdp.lcode.service.FormFieldService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.entity.LangTips;
import com.mdp.core.err.BizException;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import springfox.documentation.annotations.ApiIgnore;

import com.mdp.lcode.service.FormDefService;
import com.mdp.lcode.entity.FormDef;

@RestController
@RequestMapping(value="/**/lcode/formDef")
@Api(tags={"表单定义-操作接口"})
public class FormDefController {
	
	static Logger logger =LoggerFactory.getLogger(FormDefController.class);
	
	@Autowired
	private FormDefService formDefService;
	@Autowired
	private FormFieldService formFieldService;

	@Autowired
	private FormDataService formDataService;

	@ApiOperation( value = "表单定义-查询列表",notes=" ")
	@ApiEntityParams(FormDef.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=FormDef.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listFormDef(@ApiIgnore @RequestParam Map<String,Object> params){
		try {
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<FormDef> qw = QueryTools.initQueryWrapper(FormDef.class , params);
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = formDefService.selectListMapByWhere(page,qw,params);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}
	

	@ApiOperation( value = "表单定义-新增",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=FormDef.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addFormDef(@RequestBody FormDef formDef) {
		 formDefService.save(formDef);
         return Result.ok("add-ok","添加成功！");
	}
	@RequestMapping(value="/addFormDefAndFields")
	public Map<String,Object> addFormDefAndFields(@RequestBody FormDefVo formDefVo) {
		try{
			formDefService.addFormDefAndFields(formDefVo);
			return Result.ok().setData(formDefVo);
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
	@RequestMapping(value="/editFormDefAndFields")
	public Map<String,Object> editFormDefAndFields(@RequestBody FormDefVo formDefVo) {
		try{

			User user=LoginUtils.getCurrentUserInfo();
			formDefService.checkFormDefQx(formDefVo.getFormDef().getId(),user);
			formDefService.editFormDefAndFields(formDefVo);
			return Result.ok().setData(formDefVo);
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
	@ApiOperation( value = "表单定义-删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delFormDef(@RequestBody FormDef formDef){
		Map<String,Object> p=new HashMap<>();
		p.put("formId", formDef.getId());
		long count=formDataService.countByFormId(formDef.getId());
		if(count>0) {
 			return Result.error("has-form-data-001","该表单下还有%s条数据，请先删除数据 后删除表单",count);
		}else {

			formDefService.checkFormDefQx(formDef.getId(),LoginUtils.getCurrentUserInfo());
			formDefService.removeById(formDef.getId());
			formFieldService.putFormFields(formDef.getId(),null);
		}

        return Result.ok("del-ok","删除成功！");
	}

	@ApiOperation( value = "表单定义-修改",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=FormDef.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editFormDef(@RequestBody FormDef formDef) {
		formDefService.checkFormDefQx(formDef.getId(),LoginUtils.getCurrentUserInfo());

		formDefService.updateById(formDef);
        return Result.ok("edit-ok","修改成功！");
	}

    @ApiOperation( value = "表单定义-批量修改某些字段",notes="")
    @ApiEntityParams( value = FormDef.class, props={ }, remark = "表单定义", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=FormDef.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> params) {
        try{
            User user= LoginUtils.getCurrentUserInfo();
            formDefService.editSomeFields(params);
            return Result.ok("edit-ok","更新成功");
        }catch (BizException e) {
            logger.error("",e);
            return Result.error(e);
        }catch (Exception e) {
            logger.error("",e);
            return Result.error(e);
        }
	}

	@ApiOperation( value = "表单定义-批量删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelFormDef(@RequestBody List<FormDef> formDefs) {
	    User user= LoginUtils.getCurrentUserInfo();
        try{ 
            if(formDefs.size()<=0){
                return Result.error("formDef-batchDel-data-err-0","请上送待删除数据列表");
            }
             List<FormDef> datasDb=formDefService.listByIds(formDefs.stream().map(i-> i.getId() ).collect(Collectors.toList()));

            List<FormDef> can=new ArrayList<>();
            List<FormDef> no=new ArrayList<>();
            for (FormDef data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                formDefService.removeByIds(can);
                msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            } 
        }catch (BizException e) { 
           return Result.error(e);
        }catch (Exception e) {
            return Result.error(e);
        }


	} 

	@ApiOperation( value = "表单定义-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=FormDef.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(FormDef formDef) {
        FormDef data = (FormDef) formDefService.getById(formDef);
        return Result.ok().setData(data);
    }

}
